package com.neulogistics.contrib.transfercenter.infrastructure.persistence.converter;

import cn.hutool.json.JSONUtil;

import com.neulogistics.contrib.transfercenter.domain.model.aggregate.TransferOrder;
import com.neulogistics.contrib.transfercenter.domain.model.enumeration.TransferOrderStatus;
import com.neulogistics.contrib.transfercenter.domain.model.enumeration.TransferType;
import com.neulogistics.contrib.transfercenter.domain.model.valueobject.OrderItem;
import com.neulogistics.contrib.transfercenter.infrastructure.persistence.orm.po.TransferOrderPO;
import org.springframework.beans.BeanUtils;

public class TransferOrderEntityPOConverter {
    public static TransferOrderPO entityToPO(TransferOrder transferOrder){
        if(transferOrder == null)
            return null;

        TransferOrderPO transferOrderPO = new TransferOrderPO();
        // 复制普通属性
        BeanUtils.copyProperties(transferOrder, transferOrderPO);

        if(transferOrder.getOrderItems() != null){
            // 订单项值对象转换为json对象
            transferOrderPO.setOrderItems(JSONUtil.parseArray(transferOrder.getOrderItems()));
        }

        // 枚举类型转换
        if(transferOrder.getTransferStatus() != null){
            // 调度单状态转化为Integer
            transferOrderPO.setTransferStatus(transferOrder.getTransferStatus().id);
        }
        if(transferOrder.getTransferType() != null){
            // 调度单类型转化为Integer
            transferOrderPO.setTransferType(transferOrder.getTransferType().id);
        }

        return transferOrderPO;
    }

    public static TransferOrder POToEntity(TransferOrderPO transferOrderPO){
        if(transferOrderPO == null)
            return null;

        TransferOrder transferOrder = new TransferOrder();
        // 复制普通属性
        BeanUtils.copyProperties(transferOrderPO, transferOrder);

        // json对象转换为值对象
        transferOrder.setOrderItems(JSONUtil.toList(transferOrderPO.getOrderItems(), OrderItem.class));

        // 枚举类型转换
        // 调度单状态转换
        transferOrder.setTransferStatus(TransferOrderStatus.fromValue(transferOrderPO.getTransferStatus(), TransferOrderStatus.class));
        // 调度单类型转换
        transferOrder.setTransferType(TransferType.fromValue(transferOrderPO.getTransferType(), TransferType.class));

        return transferOrder;
    }

}
